<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Auction\AuctionBidRecordAction;
use App\Admin\Actions\Auction\AuctionCopyAction;
use App\Admin\Actions\Auction\AuctionDeleteAction;
use App\Admin\Actions\Auction\AuctionSmsMessageSwitchAction;
use App\Admin\Actions\Auction\AuctionRecommendAction;
use App\Admin\Actions\Auction\AuctionStatusDownAction;
use App\Admin\Actions\Auction\AuctionStatusUpAction;
use App\Admin\Grid\NGrid;
use App\Admin\Service\AuctionService;
use App\Library\Logic\MediaRelationLogic;
use App\Library\Logic\OperateLogLogic;
use App\Library\Traits\AdminControllerTrait;
use App\Models\AuctionModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Form\NestedForm;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Show;

class AuctionController extends AdminController
{
    use AdminControllerTrait;

    private AuctionService $service;

    protected $title = '拍卖';

    public function __construct(AuctionService $service)
    {
        $this->service = $service;
    }

    /**
     * grid
     * @return NGrid
     */
    protected function grid(): NGrid
    {
        $this->service->grid();
        $this->service->using('status');
        $this->service->using('auditStatus');
        $this->service->using('sellOut', __('l.whether'));
        $this->service->using('expired', __('l.whether'));
        $this->service->fileId();
        $this->service->column('title');
        $this->service->using('recommend', __('l.whether'));
        $this->service->using('isStart', __('l.whether'));
        $this->service->using('isEnd', __('l.whether'));
        $this->service->using('pushSwitch', __('auction.pushSwitchArr'));
        $this->service->column('startPrice,bailPrice,cappingPrice');
        $this->service->grid->column('datetime', '拍卖时间')->display(function () {
            return implode('<br>', [substr($this->start_at, 0, -3), substr($this->end_at, 0, -3)]);
        });
        $this->service->column('inc,shotCount,userCount');
        $this->service->grid->column('publisher.user_mobile', __('l.publisher'));
        $this->service->grid->disableCreateButton(false);
        $this->service->grid->disableActions(false);
        $this->service->grid->actions(function (Actions $action) {
            $action->disableDelete();
            $action->disableView(false);
            $userId = Admin::user()->user_id;
            if ($userId == config('app.superId')) $action->add(new AuctionCopyAction);
            if ($action->row->status === 0) $action->disableEdit(false);
            else $action->disableEdit();
            if ($action->row->audit_status !== 1) {
                if ($action->row->status === 0) $action->add(new AuctionStatusUpAction);
                else $action->add(new AuctionStatusDownAction);
            }
            if (!is_null($action->row->bid)) $action->add(new AuctionBidRecordAction);
            if ($action->row->status === 0) $action->add(new AuctionDeleteAction);
            $action->add(new AuctionSmsMessageSwitchAction((int)$action->row->push_switch));
            $action->add(new AuctionRecommendAction($this->row->recommend));
        });
        return $this->service->grid;
    }

    /**
     * detail
     * @param int $id
     * @return Show
     */
    protected function detail(int $id): Show
    {
        $this->service->show($id);
        $this->service->field('id,serialNumber,auditAt');
        $this->service->using('status,auditStatus');
        $this->service->using('sellOut,expired,isProtect', __('l.whether'));
        $this->service->field('okReason,failReason,sort,recommend,shotCount,userCount,title');
        $this->service->fileId();
        $this->service->category();
        $this->service->using('isFeral,stage');
        $this->service->field('startAt,endAt,startPrice,bailPrice,cappingPrice,inc,freight,brand,gene,eat,guide,sourceNumber,remark,description');
        $this->service->show->field('tag', __('l.tag'))->json();
        $this->service->show->field('main_img_ids', __('l.main_img_ids'))->unescape()->as(function () {
            $array = [];
            foreach ($this->media as $v) if ($v->type === 0) $array[] = fileIdToUrl($v->file_id);
            return $array;
        })->carousel(300, 300);
        $this->service->show->field('desc_img_ids', __('l.desc_img_ids'))->unescape()->as(function () {
            $array = [];
            foreach ($this->media as $v) if ($v->type === 1) $array[] = fileIdToUrl($v->file_id);
            return $array;
        })->carousel(300, 300);
        $this->service->show->field('video_id', __('l.video_id'))->unescape()->as(function () {
            foreach ($this->media as $v) if ($v->type === 2) {
                return "<video width=300 controls><source src='" . fileIdToUrl($v->file_id) . "'></video>";
            }
            return null;
        });
        $this->service->field('createdAt,updatedAt');
        return $this->service->show;
    }

    public function form(): Form
    {
        $this->service->form();
        $this->service->hidden('id,serialNumber,categoryIdOne~1,publishId,mainImgIds,descImgIds,videoId');
        $this->service->form->hidden('ossPrefix')->default(config('oss.url'));
        $this->service->form->ignore(['ossPrefix']);
        if ($this->service->form->isEditing()) $item = $this->service->form->model()->newQuery()
            ->find(request()->route()->parameters()['id'], [
                'id', 'category_id_one', 'category_id_two'
            ]);
        /*$list = $this->service->categoryArr($item->category_id_one ?? 1);
        $list1 = $this->service->categoryArr($item->category_id_two ?? 3);*/
        $list = $this->service->categoryArr($item->category_id_one ?? 59);
        $list1 = $this->service->categoryArr($item->category_id_two ?? 70);
        $this->service->form->column(1 / 2, function (Form $form) use ($list) {
            $form->text('title', __('l.title'))->attribute('maxlength', 30)->default(random())->required();
            $this->service->select('categoryIdTwo', $list, 1, 'categoryIdThree,/admin/ajax/category')->default(3)->required();

            $this->service->select('isProtect', __('l.whether'), 1, 0);
            $this->service->text('gene~attribute:maxlength|10');
            $this->service->currency('startPrice');
            $this->service->currency('inc');
            $this->service->text('sourceNumber~attribute:maxlength|20');
            $this->service->datetime('startAt');
//            $this->service->select('onePushStatus', __('l.whether'), 1, 0);
            $this->service->select('recommend', __('l.whether'), 1, 0);
            $this->service->text('remark~attribute:maxlength|200');
            $form->display('mainImgIds', __('l.mainImgIds'))->with(function () use ($form) {
                return view('upload_main_imgs');
            });
            $form->display('video', __('l.video'))->with(function () use ($form) {
                return view('upload_video');
            });
        });
        $this->service->form->column(1 / 2, function (Form $form) use ($list1) {
            $this->service->text('brand~attribute:maxlength|10');
            $this->service->select('categoryIdThree', $list1, 1, 7)->rules('required');
            $this->service->select('isFeral', __('auction.isFeralArr'), 1);
            $this->service->select('stage', __('auction.stageArr'), 1);
            $this->service->currency('bailPrice');
            $this->service->currency('cappingPrice');
            $this->service->number('freight');
            $this->service->datetime('endAt');
//            $form->multipleSelect('one_push', __('auction.onePushList'))
//                ->options(__('auction.onePushListArr'))->required();
            $this->service->number('sort');
            $this->service->text('guide~attribute:maxlength|200');
            $this->service->text('eat~attribute:maxlength|20');
            $this->service->text('description~attribute:maxlength|255');
            $form->display('descImgIds', __('l.descImgIds'))->with(function () use ($form) {
                return view('upload_desc_imgs');
            });
            $form->tags('tag', __('l.tag'));
            $this->service->select('status', __('auction.statusArr'), 1, 0)
                ->options(__('auction.statusArr'))->default(1)->required();
        });
        $this->service->form->column(12, function (Form $form) {
            $form->table('two_push', __('auction.twoPush'), function (NestedForm $form) {
                $form->number('timer', __('auction.timer'))->attribute('maxlength', 4)->default(5)
                    ->rules('required|integer|between:5,1440')->required();
                $form->select('crowd', '人群')->options([1 => '全部', 2 => '围观']);
                $form->multipleSelect('method', __('auction.onePushList'))->options(__('auction.onePushListArr'));
            });
        });
        $this->service->form->saving(function (Form $form) {
            if ($form->isEditing()) {
                if ($form->model()->audit_status === 1) return $this->backWith('当前审核成功,不可编辑');
                else if ($form->model()->status === 1) return $this->backWith('请先下架后再编辑');
            } else if ((float)$form->start_price < 0) return $this->backWith('起拍价不能小于0');
            else if ((float)$form->bail_price < 0) return $this->backWith('保证金不能小于0');
            else if ((float)$form->inc <= 0) return $this->backWith('加价幅度必须大于0');
            if (is_null($form->category_id_three)) return $this->backWith('子类目不能为空');
            $arr = [];
            if (!empty($form->two_push)) {
                foreach ($form->two_push as $v) {
                    if (in_array($v['timer'], $arr)) return $this->backWith('时间(分钟)不可重复');
                    $arr[] = $v['timer'];
                }
            }
            if (is_null($form->category_id_one)) {
                $form->category_id_one = 1;
                $form->category_id_two = 3;
                $form->category_id_three = 7;
            }
            $userId =config('app.superId');
            if(!empty(Admin::user()->admin_type)){
                $userId = Admin::user()->user_id;
            }
            if (is_null($form->is_protect)) $form->is_protect = 0;
            if (is_null($form->is_feral)) $form->is_feral = 0;
            if (is_null($form->publish_id)) $form->publish_id = $userId;
            if ($form->isCreating()) $form->serial_number = AuctionModel::getSerialNumber();
            if ($form->capping_price * 1 <= 0) $form->capping_price = null;
            if (empty($form->main_img_ids)) $form->main_img_ids = __('com.defaultImg');
            if (is_null($form->title)) $form->title = random();
            if ((int)$form->one_push_status === 1) {
                $onePush = [];
                if (!empty($form->one_push)) foreach ($form->one_push as $v) if (!is_null($v)) $onePush[] = (int)$v;
                $form->one_push = empty($onePush) ? null : $onePush;
            } else $form->one_push = null;
            return true;
        });
        $this->service->form->saved(function (Form $form) {
            echo 11;die;
            $where = ['objectType' => 1, 'objectId' => $form->model()->id];
            if (!empty($form->main_img_ids)) {
                $mainImgIds = explode(',', $form->main_img_ids);
                foreach ($mainImgIds as $v) $arr[] = array_merge($where, ['fileId' => $v, 'type' => 0]);
                $form->model()->file_id = $mainImgIds[0];
                $form->model()->save();
            }
            if (!empty($form->desc_img_ids)) {
                $mainImgIds = explode(',', $form->desc_img_ids);
                foreach ($mainImgIds as $v) $arr[] = array_merge($where, ['fileId' => $v, 'type' => 1]);
            }
            if (!empty($form->video_id)) $arr[] = array_merge($where, ['fileId' => $form->video_id, 'type' => 2]);
            if ($form->isEditing()) MediaRelationLogic::deleteByWhere($where);
            MediaRelationLogic::insert($arr ?? []);
        });
        $this->service->form->setWidth(10);
        OperateLogLogic::add(Admin::user()->user_id);
        Admin::script("$('h4.pull-right').parent().addClass('col-sm-1').removeClass('col-sm-2');");
        return $this->service->form->confirm('确定提交吗?');
    }
}
